每當存取一個Optional變數,Xcode會強迫執行確認此Optional是否有值,以避免程式出問題。
var programmingLanguage: String?
programmingLanguage = "swift"
print("I'm lerning " + programmingLanguage!)
//I'm learnign Swift
以下變數因尚未賦值,所以目前是nil,將會報錯:
var programmingLanguage: String?
print("I'm lerning " + programmingLanguage!)
var programmingLanguage: String? = "Swift"
if programmingLanguage != nil {
programmingLanguage = "I'm learning " + programmingLanguage!
}
//I'm learnign Swift
let programmingLanguage: String?
programmingLanguage = "String" or nil
if let programmingLanguageWithValue = programmingLanguage{
var message = "I'm learning " + programmingLanguageWithValue
}else {
var message = "What are you learning?"
}
//"String"有值:執行if let
//nil無值:執行else
var programmingLanguage: String? = "Swift"
var programmingLanguageWithValue = programmingLanguage ?? "Why not?"
//Swift
programmingLanguage = nil
programmingLanguageWithValue = programmingLanguage ?? "Why not?"
//why not?